package com.yami.shop.mystery.common.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.event.EsMysteryBoxUpdateEvent;
import com.yami.shop.bean.event.EsProductUpdateEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.util.OssMultipartFile;
import com.yami.shop.mystery.common.dao.ActivitySubjectMapper;
import com.yami.shop.mystery.common.model.ActivityPresell;
import com.yami.shop.mystery.common.model.ActivityProd;
import com.yami.shop.mystery.common.model.ActivitySubject;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.service.ActivityPresellService;
import com.yami.shop.mystery.common.service.ActivityProdService;
import com.yami.shop.mystery.common.service.ActivitySubjectService;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import com.yami.shop.service.AttachFileService;
import com.yami.shop.service.ProdParameterService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class ActivitySubjectServiceImpl extends ServiceImpl<ActivitySubjectMapper, ActivitySubject> implements ActivitySubjectService {

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private AttachFileService attachFileService;
    @Autowired
    private ActivityPresellService activityPresellService;
    @Autowired
    private ActivityProdService activityProdService;
    @Autowired
    private ProductService productService;
    @Autowired
    private MysteryBoxService mysteryBoxService;
    @Autowired
    private ApplicationEventPublisher eventPublisher;
    @Autowired
    private ProdParameterService prodParameterService;

    @Override
    public void createQrcode(Long activitySubjectId, Long shopId, boolean isContainFree, String activityId) {
        QrConfig config = new QrConfig(300, 300);
        // 获取微发行链接地址 -- 暂时用 shopId 保存
        String url = "";
        if (isContainFree) {
            url = sysConfigService.getValue("V_URL") + "/#/?shopId=" + shopId + "&activitySubjectId=" + activitySubjectId + "&type=2";
            // 修改商品链接信息
            updateQrcode(activitySubjectId, shopId, activityId);
        } else {
            url = sysConfigService.getValue("V_URL") + "/#/?shopId=" + shopId + "&activitySubjectId=" + activitySubjectId;
            // 修改商品链接信息
            updateQrcode(activitySubjectId, shopId, activityId);
        }
        BufferedImage qrgenerate = QrCodeUtil.generate(url, config);
        //保存图片
        ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
        //读文件
        try {
            ImageIO.write(qrgenerate, "jpg", qrOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        MultipartFile ossMultipartFile = new OssMultipartFile("111.jpg", ".jpg", qrOutputStream.toByteArray());
        try {
            String fileName = attachFileService.uploadFile(ossMultipartFile.getBytes(), UUID.fastUUID() + ".jpg");
            // 保存链接信息
            UpdateWrapper<ActivitySubject> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", activitySubjectId);
            updateWrapper.set("link_addr", url);
            updateWrapper.set("qrcode_addr", fileName);
            this.update(updateWrapper);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void updateQrcode(Long activitySubjectId, Long shopId, String activityId) {
        String[] activityIds = activityId.split(",");
        for (String activity : activityIds) {
            // 获取活动信息
            ActivityPresell byId = activityPresellService.getById(activity);
            List<ActivityProd> activityProds = activityProdService.listByActivityId(Long.parseLong(activity));
            for (ActivityProd activityProd : activityProds) {
                // 商品
                if (byId.getBlindType() == 0) {
                    // 生成Link 地址
                    String url = sysConfigService.getValue("V_URL") + "/#/?shopId=" + shopId + "&prodId=" + activityProd.getProdId() + "&activitySubjectId=" + activitySubjectId + "&activityId=" + activity;
                    QrConfig config = new QrConfig(300, 300);
                    BufferedImage qrgenerate = QrCodeUtil.generate(url, config);
                    //保存图片
                    ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
                    //读文件
                    try {
                        ImageIO.write(qrgenerate, "jpg", qrOutputStream);
                        MultipartFile ossMultipartFile = new OssMultipartFile("111.jpg", ".jpg", qrOutputStream.toByteArray());
                        String fileName = attachFileService.uploadFile(ossMultipartFile.getBytes(), UUID.fastUUID() + ".jpg");
                        // 预售活动 创建 tz_activity_prod 二维码
                        if ("1".equals(byId.getActivityType())) {
                            activityProd.setLinkAddr(url);
                            activityProd.setQrcodeAddr(fileName);
                            activityProdService.updateById(activityProd);
                        }
                        // 其他活动 修改商品表 二维码
                        else {
                            Product product = productService.getById(activityProd.getProdId());
                            product.setLinkAddr(url);
                            product.setQrcodeAddr(fileName);
                            boolean update = productService.updateById(product);
                            if (update) {
                                removeCache(product.getProdId());
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 盲盒
                else if (byId.getBlindType() == 1) {
                    MysteryBox box = mysteryBoxService.getById(activityProd.getProdId());
                    box.setLinkAddr(box.getLinkAddr() + "&activitySubjectId=" + activitySubjectId);
                    QrConfig config = new QrConfig(300, 300);
                    BufferedImage qrgenerate = QrCodeUtil.generate(box.getLinkAddr(), config);
                    //保存图片
                    ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
                    //读文件
                    try {
                        ImageIO.write(qrgenerate, "jpg", qrOutputStream);
                        MultipartFile ossMultipartFile = new OssMultipartFile("111.jpg", ".jpg", qrOutputStream.toByteArray());
                        String fileName = attachFileService.uploadFile(ossMultipartFile.getBytes(), UUID.fastUUID() + ".jpg");
                        box.setQrcodeAddr(fileName);
                        boolean update = mysteryBoxService.updateById(box);
                        eventPublisher.publishEvent(new EsMysteryBoxUpdateEvent(box.getId(), null, EsOperationType.UPDATE));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    }

    // 清除缓存 修改ES
    public void removeCache(Long prodId) {
        productService.removeProdCacheByProdId(prodId);
        prodParameterService.removeCacheByProdId(prodId);
        eventPublisher.publishEvent(new EsProductUpdateEvent(prodId, null, EsOperationType.UPDATE));
    }

}

